<template>
  <div class="comment-panel">
    <div class="comment-title">
      <div class="title">
        评论<span class="comment-count">{{ dataSource?.totalCount }}</span>
      </div>
      <div :class="['order-type-item', orderType == 0 ? 'active' : '']" @click="changeOrder(0)">
        最热
      </div>
      <el-divider direction="vertical"></el-divider>
      <div :class="['order-type-item', orderType == 1 ? 'active' : '']" @click="changeOrder(1)">
        最新
      </div>
    </div>
    <div class="comment-content-panel">
      <VideoCommentSend :send-type="0" :show-send="showComment"></VideoCommentSend>
    </div>
    <div class="comment-list" v-if="showComment">
      <DataLoadMoreList
        layout-type="list"
        load-end="没有更多评论了"
        :data-source="dataSource"
        :loading="loadingData"
        @load-data="loadCommentList"
      >
        <template #default="{ data }">
          <VideoCommentItem :data="data"></VideoCommentItem>
        </template>
      </DataLoadMoreList>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ACTION_TYPE } from '@/utils/Constants'
import { videoCommentHttpRequest } from '@/services/api/video'
import { computed, inject, onMounted, onUnmounted, provide, ref } from 'vue'
import { useRoute } from 'vue-router'
import VideoCommentSend from './VideoCommentSend.vue'
import VideoCommentItem from './VideoCommentItem.vue'
import { mitter } from '@/eventbus/eventBus'

const route = useRoute()

const loadingData = ref(false)
const dataSource = ref<any>()

const orderType = ref(0)

//排序规则
const changeOrder = (type: number) => {
  orderType.value = type
  loadCommentList()
}
//获取视频详情数据
const videoInfoDetail: any = inject('videoInfo')
//是否开启评论区
const showComment = computed(() => {
  console.log(videoInfoDetail.value.videoInfo, '@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')

  return (
    videoInfoDetail.value.videoInfo.interaction == null ||
    videoInfoDetail.value.videoInfo.interaction.indexOf('0') == -1
  )
})
//获取评论数据
const loadCommentList = async (top = 0) => {
  if (!showComment.value) {
    return
  }
  const pageNo = top === null || top === 0 ? 0 : dataSource.value?.pageNo || top
  loadingData.value = true
  const res = await videoCommentHttpRequest(route.params.videoId as string, orderType.value, pageNo)
  loadingData.value = false
  const userActionMap: any = {}
  const userActionList = res.data.userActionList

  //将用户行为按commentId分类存储到映射表中
  userActionList.forEach((item) => {
    userActionMap[item.commentId] = item
  })
  const commentData = res.data.commentData
  commentData.list.forEach((item) => {
    //为每条评论设置激活状态（如是否点赞或者踩）
    setCommentActive(userActionMap, item)
    if (item.children) {
      item.children.forEach((sub) => {
        setCommentActive(userActionMap, sub)
      })
    }
  })
  //合并新旧数据
  const dataList = dataSource.value?.list // 获取当前已有的评论列表
  //用Object.assign合并新旧分页数据
  dataSource.value = Object.assign({}, commentData)
  //如果是加载更多（非第一页），则拼接新旧评论列表
  if (commentData.pageNo > 1) {
    dataSource.value.list = dataList.concat(commentData.list)
  }
}

//显示是否高亮(点赞或踩)
const setCommentActive = (userActionMap: any, item: any) => {
  //从userActionMap找到对应的数据
  const userAction = userActionMap[item.commentId]
  //如果在userActionMap中找到该数据证明是点赞否则相反
  if (userAction) {
    if (ACTION_TYPE.COMMENT_LIKE.value == userAction.actionType) {
      item.likeCountActive = true
    } else if (ACTION_TYPE.COMMENT_HATE.value == userAction.actionType) {
      item.hateCountActive = true
    }
  }
}
loadCommentList()

//展示回复评论的信息输入框
const showReplyHandler = (commentId: number) => {
  dataSource.value.list.forEach((item: any) => {
    if (item.commentId != commentId) {
      item.showReply = false
    } else {
      item.showReply = true
    }
  })
}
provide('showReply', showReplyHandler)

onMounted(() => {
  mitter.on('postCommentSuccess', async (comment: any) => {
    //如果是一级评论
    if (comment.pcommentId == 0) {
      dataSource.value.list.unshift(comment)
      if (!dataSource.value.totalCount) {
        dataSource.value.totalCount = 1
      } else {
        dataSource.value.totalCount++
      }
    } else {
      //TODO 二级评论不作数服务端还没有修改
      //找到当前你正在回复的评论
      const curComment = dataSource.value.list.find((item: any) => {
        return item.commentId == comment.pcommentId
      })
      if (!curComment) {
        return
      }
      if (!curComment.children) {
        curComment.children = []
      }
      //给当前的评论数据添加子级评论
      curComment.children.push(comment)
    }
  })
  mitter.on('topCommentCallback', async () => {
    //置顶评论成功后重新加载评论数据
    await loadCommentList()
  })
  mitter.on('delUserCommentCallback', (data: any) => {
    const { commentId, pcommentId } = data
    if (pcommentId == 0) {
      //把删除的父级评论过滤掉
      dataSource.value.list = dataSource.value.list.filter((item: any) => {
        return item.commentId != commentId
      })
      dataSource.value.totalCount--
    } else {
      //过滤子评论
      const pComment = dataSource.value.list.find((item: any) => {
        return item.commentId == pcommentId
      })

      pComment.children = pComment.children.filter((item: any) => {
        return item.commentId != commentId
      })
    }
  })
})

onUnmounted(() => {
  mitter.off('topCommentCallback')
  mitter.off('delUserCommentCallback')
  mitter.off('postCommentSuccess')
})
</script>

<style lang="less" scoped>
.comment-panel {
  margin-top: 20px;
  .comment-title {
    display: flex;
    align-items: center;
    font-size: 15px;
    .title {
      font-size: 20px;
      font-weight: 500;
      .comment-count {
        margin-left: 5px;
        font-size: 14px;
        margin-right: 30px;
        color: var(--text2);
      }
    }
    .order-type-item {
      cursor: pointer;
    }
    .active {
      color: var(--blue);
    }
  }
  .comment-content-panel {
    padding-left: 10px;
    position: relative;
    .comment-list {
      padding-bottom: 20px;
    }
  }
}
</style>
